<template>
  <div class="finish-goods-container">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新建成品
      </el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="搜索成品名称/编码"
          clearable
          style="width: 300px; margin-left: 15px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="paginatedData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column prop="sku" label="成品编码" width="100" align="center" />
      <el-table-column prop="name" label="成品名称" width="120" align="center" />

      <el-table-column label="商品图" width="120" align="center">
        <template #default="{ row }">
          <el-image
              :src="row.productImage"
              :preview-src-list="[row.productImage]"
              fit="cover"
              style="width: 60px; height: 60px"
              :preview-teleported="true"
          />
        </template>
      </el-table-column>

      <el-table-column label="组成零件" width="600" align="center">
        <template #default="{ row }">
          <el-tag
              v-for="comp in row.components"
              :key="comp.id"
              type="info"
              class="component-tag"
          >

            {{ getComponentName(comp.componentId) }} ×{{ comp.quantity }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" align="center" />
      <el-table-column label="最后更新" width="180" align="center">
        <template #default="{ row }">
          <div class="update-info">
            <span class="operator">{{ row.operator }}</span>
            <span class="time">{{ formatTime(row.updated_at) }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.finished_id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="filteredData.length"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑成品' : '新建成品'"
        width="800px"
    >
      <el-form
          :model="formData"
          label-width="100px"
          ref="formRef"
          :rules="formRules"
      >
        <el-form-item label="成品编码" prop="sku">
          <el-input
              v-model="formData.sku"
              placeholder="FW-0001"
              style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="成品名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="请输入成品名称"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input
              type="number"
              v-model="formData.stock"
              placeholder="请输入库存"
          />
        </el-form-item>



        <el-form-item label="组成零件" prop="components">
          <div class="bom-editor">
            <el-table :data="formData.components" border>
              <el-table-column width="350">
                <template #header>
                  <el-button
                      type="primary"
                      size="small"
                      @click="addComponent"
                  >
                    <el-icon><Plus /></el-icon>添加零件
                  </el-button>
                </template>
                <template #default="{ $index }">
                  <el-select
                      v-model="formData.components[$index].componentId"
                      placeholder="选择零件"
                      filterable
                      style="width: 100%"
                  >
                    <el-option
                        v-for="c in components"
                        :key="c.id"
                        :label="`${c.name}`"
                        :value="c.id"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="数量" width="180">
                <template #default="{ $index }">
                  <el-input-number
                      v-model="formData.components[$index].quantity"
                      :min="1"
                      controls-position="right"
                  />
                </template>
              </el-table-column>

              <el-table-column width="70">
                <template #default="{ $index }">
                  <el-button
                      type="danger"
                      size="small"
                      @click="removeComponent($index)"
                  >
                    <el-icon><Close /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleImageUpload"
          >
            <el-image
                v-if="formData.productImage"
                :src="formData.productImage"
                class="preview-image"
                fit="cover"
            />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm"
        >
          {{ isEditMode ? '保存修改' : '确认添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Close } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {addFinishGoods, getAllFinishGoodS, getAllProducts, updateFinishGoods} from "@/api/auth.js";

// 模拟数据
const components = ref([  // 基础零件列表
  { id: 1, name: '手机屏幕', sku: 'COM-001' },
  { id: 2, name: '锂电池', sku: 'COM-002' },
  { id: 3, name: '主板', sku: 'COM-003' }
])

const mockData = ref([  // 成品数据
  {
    id: 1,
    sku: 'FW-1001',
    name: '智能手机',
    productImage: 'https://dummyimage.com/200x200/eee/999',
    components: [
      { components: 1, quantity: 2 },
      { components: 2, quantity: 1 },
      { components: 3, quantity: 1 }
    ],
    operator: '管理员',
    updateTime: '2024-03-20 14:30:00',
    stock:10
  }
])
const initData=async ()=>{
  try {
    const res=await getAllFinishGoodS()
    if(res.code===200){
      mockData.value=res.data

    }else {
      ElMessage.error(res.message)
    }
  }catch (e){
    ElMessage.error(e)
  }
  try {
    const res=await getAllProducts()
    if(res.code===200){
      components.value=res.data
    }else {
      ElMessage.error(res.data)
    }
  }catch (e){
    ElMessage.error(e)
  }





}
onMounted(()=>{
  initData()
})

// 响应式状态
const loading = ref(false)
const searchKeyword = ref('')
const dialogVisible = ref(false)
const isEditMode = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  sku: '',
  name: '',
  stock:1,
  components: [],
  productImage:''
})
const handleImageUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.productImage = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 表单验证规则
const formRules = reactive({
  sku: [
    { required: true, message: '请输入成品编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入成品名称', trigger: 'blur' }
  ],
  components: [
    {
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error('至少需要添加一个零件'))
        } else if (value.some(c => !c.componentId)) {
          callback(new Error('存在未选择的零件'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

// 图片上传相关
const fileList = ref()

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10
})

// 计算属性
const filteredData = computed(() => {
  return mockData.value.filter(item =>
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.sku.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 方法定义
const getComponentName = (id) => {
  const component = components.value.find(c => c.id === id)
  return component ? `${component.name} ` : '未知零件'
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const handleAdd = () => {
  isEditMode.value = false
  Object.assign(formData, {
    id: null,
    sku: '',
    name: '',
    productImage: '',
    components: []
  })
  fileList.value = []
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, {
    ...row,
    components: row.components.map(c => ({ ...c }))
  })
  fileList.value = row.productImage
  dialogVisible.value = true

}

const addComponent = () => {
  formData.components.push({
    component_id: null,
    quantity: 1
  })
}

const removeComponent = (index) => {
  formData.components.splice(index, 1)
}




const handleRemove = (file) => {
  const index = formData.images.findIndex(url => url === file.url)
  if (index !== -1) {
    formData.images.splice(index, 1)
  }
}

const submitForm = async () => {

  try {


    if (isEditMode.value) {
      const index = mockData.value.findIndex(item => item.finished_id === formData.finished_id)
      mockData.value.splice(index, 1, { ...formData })
    try {
      const res=await updateFinishGoods(formData)
      if(res.code===200){
        ElMessage.success('修改成功')
      }else {
        ElMessage.error(res.message)
      }
    }catch (e){
        ElMessage.error(e)
    }
      dialogVisible.value = false
    await initData();




    } else {
     try {
       const res=await addFinishGoods(formData)
       if(res.code===200){
         ElMessage.success('添加成功')
       }else {
         ElMessage.error(res.message)
       }}
      catch (e){
       ElMessage.error(e)
      }
      dialogVisible.value = false
      await initData()
     }

     }




   catch (error) {
    console.error('提交失败:', error)
  }

}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该成品？此操作不可恢复！', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 500))
    const index = mockData.value.findIndex(item => item.finished_id === id)
    if (index !== -1) mockData.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).finally(() => {
    loading.value = false
  })
}
</script>

<style scoped>
.finish-goods-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.component-tag {
  margin: 2px 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.bom-editor {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.update-info {
  display: flex;
  flex-direction: column;
  line-height: 1.5;

  .time {
    color: #999;
    font-size: 12px;
  }
}

:deep(.el-upload-list__item) {
  transition: all 0.3s ease;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.preview-image {
  width: 200px;
  height: 200px;
  border-radius: 4px;
  cursor: pointer;
}
.upload-icon {
  width: 200px;
  height: 200px;
  font-size: 28px;
  color: #8c939d;
  background: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>